import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'manager/fcl_bmf_location_manager.dart';
import 'models/flutter_baidu_location.dart';


class LocationPage extends StatefulWidget {
  const LocationPage({super.key, required this.title});
  final String title;

  @override
  LocationPageState createState() => LocationPageState();
}

class LocationPageState extends State<LocationPage> {
  var selectAreaText = ''.obs;

  @override
  void initState() {
    super.initState();
    WidgetsFlutterBinding.ensureInitialized();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      bool isPms = await checkPermission();
      if (!isPms) {
        return;
      }
      // ignore: use_build_context_synchronously
      initLocation(context); 
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: Column(
          children: [
            Obx(() {
              return Container(
                margin: const EdgeInsets.only(top: 100,bottom: 60),
                child: Text(
                '当前位置：${selectAreaText.value}',
                style: TextStyle(fontSize: 16),
                maxLines: 10,
                overflow: TextOverflow.ellipsis,
              ),
              );
            }),
            InkWell(
              onTap: () async {
                selectAreaText.value = '';
                bool isPms = await checkPermission();
                if (!isPms) {
                  return;
                }
                // ignore: use_build_context_synchronously
                beginLocation(context: context);
              },
              child: Container(
                margin: const EdgeInsets.only(top: 10),
                padding: const EdgeInsets.all(10),
                color: Colors.blue,
                child: const Center(
                  child: Text('开始定位'),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  /// 开始定位
  void beginLocation({BuildContext? context}) async {
    try {
      await FclBmfLocationManager().startLocation(block: (FlsBaiduLocation? location,String? errStr) {
        if (location == null && errStr == null) {
          return;
        }
        if (location != null && errStr == null) {
          if (location.errorCode != null) {
            selectAreaText.value = '${location.errorCode}:${location.errorInfo}';
            return;
          }

          print('location: ${location.latitude}, ${location.longitude} adCode: ${location.adCode}');
          String locAreaText =
              '${location.province ?? ''} ${location.city ?? ''} ${location.district ?? ''}';
          selectAreaText.value = locAreaText;
        } else {
          selectAreaText.value = errStr ?? '定位失败';
        }
      });
    } catch (e) {
      print('beginLocation error: $e');
      selectAreaText.value = e.toString();
    }
  }
  /// 检查权限
  Future<bool> checkPermission () async {
    try {
      bool isPms = await FclBmfLocationManager().checkPermission();
      return isPms;
    }  catch (e) {
      selectAreaText.value = e.toString();
      print('fbmf---->checkPermission error: $e');
      return false;
    }
  }

  Future<void> initLocation(BuildContext context) async {
    try {
      String? errorTips = await FclBmfLocationManager().initLocation();
      if (errorTips == '未实现的平台') {
        selectAreaText.value = '请手动选择位置';
        return;
      }
      if (errorTips != null) {
        print('initForBeginLocation error: $errorTips');
        selectAreaText.value = '定位失败，请手动选择位置';
        return;
      }
      beginLocation();
    } catch (e) {
      print('initForBeginLocation error: $e');
      selectAreaText.value = e.toString();
    }
  }
}

